import request from '@/utils/request'
import axios from 'axios'

// 获取临时密钥
export function getCredential(ext, path) {
  return request({
    url: '/cos/credential',
    method: 'get',
    params: { ext, path }
  })
}

/**
 * 文件上传
 * @param {*} opt 临时密钥参数
 * @param {*} file 上传的文件
 * @returns
 */
export function uploadFile(opt, file) {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('key', opt.cosKey)
    formData.append('policy', opt.policy)
    formData.append('q-sign-algorithm', opt.qSignAlgorithm)
    formData.append('q-ak', opt.qAk)
    formData.append('q-key-time', opt.qKeyTime)
    formData.append('q-signature', opt.qSignature)
    formData.append('file', file)
    // 如果服务端用了临时密钥计算，需要传 x-cos-security-token
    if (opt.securityToken) {
      formData.append('x-cos-security-token', opt.securityToken)
    }
    // 发送 POST 请求到 COS
    axios
      .post(`https://${opt.cosHost}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((response) => {
        if (![200, 204].includes(response.status)) {
          resolve(response)
        } else {
          const fileUrl = `https://${opt.cosHost}/` + camSafeUrlEncode(opt.cosKey).replace(/%2F/g, '/')
          resolve(fileUrl)
        }
      })
      .catch((error) => {
        console.error('Upload failed', error.response)
      })
  })
}

// 对更多字符编码的 url encode 格式
export function camSafeUrlEncode(str) {
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A')
}
